package ltd.hyangyang.rpc.core.remoting.server;


import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import ltd.hyangyang.rpc.common.bean.Request;
import ltd.hyangyang.rpc.common.bean.Response;
import ltd.hyangyang.rpc.common.constant.RemoteMsgConstant;
import ltd.hyangyang.rpc.common.utils.SingletonFactory;
import ltd.hyangyang.rpc.core.remoting.CustomHandler;
import ltd.hyangyang.rpc.core.remoting.client.UnfinishChannel;
import ltd.hyangyang.rpc.core.remoting.server.RemotingHandler;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

public class RpcServerHandler extends CustomHandler {

    Logger logger = Logger.getGlobal();

    RpcServerNetty rpcServerNetty;

    public static ConcurrentHashMap<String, Channel> connectChannels = new ConcurrentHashMap<>();


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Response response = null;
        //服务端读取消息
        Request request= (Request) msg;
        //根据request调用服务端方法
        if (request.getMsgType().equals(RemoteMsgConstant.PING)){
            //如果消息是ping，则返回pong消息
            Response.builder().msgType(RemoteMsgConstant.PONG);
        }else if (request.getMsgType().equals(RemoteMsgConstant.PONG)){
            //如果消息是pong，打印channel的id
        }else {
            RemotingHandler remotingHandler = new RemotingHandler();
            Object result = remotingHandler.invokeFunction(request);
            logger.info(result.toString());
            response = Response.success(result,request.getRequestId());
        }
        //将消息发送到客户端
        ctx.writeAndFlush(response);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        String channelId = channel.id().asShortText();
        connectChannels.put(channelId,channel);
    }

    //长时间没有访问，ping客户端口，如果客户端口关闭，则释放channel资源
    @Override
    public void handlerAllIdle(Channel channel) {
        //获取单例nettyServer
        rpcServerNetty = SingletonFactory.getSingletonBean(RpcServerNetty.class);
        rpcServerNetty.sendPingMsg(channel);
    }
}
